const md5 = require('./md5.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
/*方法说明
 *@method requstDelete post请求
 *@param{string} url 请求url
 *@param{object} data 请求参数
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const requstDelete = (url, data) => {
  return requst(url, 'DELETE', data)
}
/*方法说明
 *@method requst 封装Request请求方法
 *@param{string} url 请求url
 *@param{string} methods 请求方法（OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT）
 *@param{object} data 请求参数
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const requst = (url, method, data = {}) => {
  data.token = '';
  const token = wx.getStorageSync('token') || '';
  if(token && token !== ''){
    data.token = token;
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      header: {
        "token":token,
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: method.toUpperCase(), // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      success: function (res) {
        if (res.data.status == -100 || res.data.status == -101 || res.data.status == -102) {
          wx.navigateTo({
            url: '/page/tabBar/login/login',
          })
          return
        }
        setTimeout(() => {
          wx.hideNavigationBarLoading()
        }, 500)
        resolve(res.data)
      },
      fail: function (msg) {
        setTimeout(() => {}, 500)
        reject('网络连接失败,请检查网络状况')
      }
    })
  })
}

/*方法说明
 *@method requstGet get请求
 *@param{string} url 请求url
 *@param{object} data 请求参数
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const requstGet = (url, data) => {
  return requst(url, 'GET', data)
}

/*方法说明
 *@method requstPost post请求
 *@param{string} url 请求url
 *@param{object} data 请求参数
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const requstPost = (url, data) => {
  return requst(url, 'POST', data)
}



/*方法说明
 *@method checkSession 微信检测登录态是否过期
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const checkSession = () => {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: resolve,
      fail: reject
    })
  })
}
/*方法说明
 *@method requstPut post请求
 *@param{string} url 请求url
 *@param{object} data 请求参数
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const requstPut = (url, data) => {
  return requst(url, 'PUT', data)
}


/*方法说明
 *@method getSetting 微信获取权限
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const getSetting = () => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: resolve,
      fail: reject
    })
  })
}

/*方法说明
 *@method getUserInfo 微信获取用户信息（已经授权）
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const getUserInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      withCredentials: true,
      lang: 'zh_CN',
      success: resolve,
      fail: reject
    })
  })
}


/*方法说明
 *@method login 微信静默登录
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */

const login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: resolve,
      fail: reject
    })
  })
}

/*方法说明
 *@method getLocation 微信获取定位
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const getLocation = () => {
  return new Promise((resolve, reject) => {
    // wx.getLocation({
    //   type: 'gcj02',
    //   success: resolve,
    //   fail: reject
    // })
  })
}


/*方法说明
 *@method getLocation 微信获取定位
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const mySetStorage = (key, val) => {
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key: key,
      data: val,
      success: resolve,
      fail: reject
    })
  })
}

/*方法说明
 *@method mySetStorage 封装添加本地存储
 *@return {promise} resolve 成功回调
 *@return {promise} reject 失败回调
 */
const myGetStorage = (key) => {
  return new Promise((resolve, reject) => {
    wx.getStorage({
      key: 'key',
      success: resolve,
      fail: reject
    })
  })
}

/*方法说明
 *@method getTimestamp 获取10位时间戳
 *@return {string} 10位时间戳
 */
const getTimestamp = () => {
  let timestamp = (new Date()).getTime().toString();
  return timestamp.substr(0, 10);
}

/*方法说明
 *@method passwordMd5 md5加密码
 *@param{string} params 将要拼接的字符串
 *@return {string} md5加密字符串
 */
const passwordMd5 = (params) => {
  const API_SECRET_KEY = "16ae8fbebb80ace4";
  let password = API_SECRET_KEY + params;
  return md5(password)
}

/*方法说明
 *@method getSign 生成签名
 *@param{object} params 传递的参数
 *@param{string} time 时间戳
 *@return {string} 签名字符串
 */
const getSign = (params, time) => {
  const API_SECRET_KEY = "beb2702df179a4ac";
  if (typeof params == "object") {
    let arr = [];
    let values = [];
    for (var i in params) {
      arr.push(i);
    }
    let newArr = arr.sort();
    newArr.forEach((item, index) => {
      values.push(params[item]);
    })
    let valStr = values.join("");
    let sign = valStr + time + API_SECRET_KEY;
    return md5(sign)
  }
}

/*方法说明
 *@method getSignData 生成带签名的json
 *@param{object} json 请求数据
 *@return {object} 带签名的json
 */
const getSignData = (json) => {
  let timestamp = getTimestamp();
  json.sign = getSign(json, timestamp);
  json.time = timestamp;
  return json;
}
//多张图片上传
function uploadimg(data) {
  var that = this,
    i = data.i ? data.i : 0, //当前上传的哪张图片
    success = data.success ? data.success : 0, //上传成功的个数
    fail = data.fail ? data.fail : 0; //上传失败的个数
  wx.uploadFile({
    url: data.url,
    filePath: data.path[i],
    name: 'file', //这里根据自己的实际情况改
    formData: null, //这里是上传图片时一起上传的数据
    success: (resp) => {
      success++; //图片上传成功，图片上传成功的变量+1
      console.log(resp)
      console.log(i);
      //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
    },
    fail: (res) => {
      fail++; //图片上传失败，图片上传失败的变量+1
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: () => {
      console.log(i);
      i++; //这个图片执行完上传后，开始上传下一张
      if (i == data.path.length) { //当图片传完时，停止调用          
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
      } else { //若图片还没有传完，则继续调用函数
        console.log(i);
        data.i = i;
        data.success = success;
        data.fail = fail;
        that.uploadimg(data);
      }

    }
  });
}

const arrTrans = (num, arr) => { // 一维数组转换为二维数组
  const iconsArr = []; // 声明数组
  arr.forEach((item, index) => {
    const page = Math.floor(index / num); // 计算该元素为第几个素组内
    if (!iconsArr[page]) { // 判断是否存在
      iconsArr[page] = [];
    }
    iconsArr[page].push(item);
  });
  return iconsArr;
}
/*函数节流*/
function throttle(func, interval) {
  let previous = 0;
  interval = interval || 1000;
  return function (...args) {
    console.log(this)
    const context = this;
    const now = Date.now();
    if (now - previous > interval) {
      previous = now;
      func.apply(context, args);
    }
  };
}
/*函数防抖*/
function debounce(func, interval) {
  let timeout;
  interval = interval || 1000;
  return function (...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, interval);
  };
}

module.exports = {
  formatTime: formatTime,
  get: requstGet,
  post: requstPost,
  delete: requstDelete,
  put: requstPut,
  requst,
  getUserInfo,
  login,
  checkSession,
  getSetting,
  getLocation,
  mySetStorage,
  myGetStorage,
  getSignData,
  getTimestamp,
  md5,
  passwordMd5,
  arrTrans,
  throttle,
  debounce,
}